<template>
  <div class="app-container">
    <el-form :model="formData" :rules="formRules" ref="formData" label-width="100px">
      <!-- 基本信息 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="productName">
            <el-input v-model="formData.productName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品分类" prop="categoryCode">
            <el-cascader ref='categoryCascader' style="width:100%" v-model="formData.categoryCode" :options="categoryList" clearable :props="{label: 'categoryName',value: 'categoryCode'}" @change="onChangeCascader"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品原价" prop="price">
            <el-input-number style="width:100%" v-model="formData.price" controls-position="right" :min="0" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品售价" prop="soldPrice">
            <el-input-number style="width:100%" v-model="formData.soldPrice" controls-position="right" :min="0" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品库存" prop="stock">
            <el-input-number style="width:100%" v-model="formData.stock" controls-position="right" :min="0"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设置为热门" prop="isHot">
            <el-switch v-model="formData.isHot" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 轮播图上传 -->
      <el-row>
        <el-col :span="18">
          <el-form-item label="轮播图上传">
            <upload-image :defaultList='swiperImageList' color="#1890ff" class="editor-upload-btn" :limit="3" @successCBK="syncImageList($event,imageType.swiper)" />
          </el-form-item>
        </el-col>
        <el-col :span="6"></el-col>
      </el-row>
      <!-- 缩略图上传 -->
      <el-row>
        <el-col :span="18">
          <el-form-item label="缩略图上传">
            <upload-image :defaultList="thumbImageList" color="#1890ff" class="editor-upload-btn" @successCBK="syncImageList($event,imageType.thumb)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
        </el-col>
      </el-row>

      <!-- 商品规格 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="启用产品规格">
            <el-switch v-model="formData.isEnableSpec" :active-value="1" :inactive-value="0" @change="onChangeSpecSwitch"></el-switch>
            <div v-show="formData.isEnableSpec">
              <SkuForm ref="skuForm" :source-attribute="sourceAttribute" :attribute.sync="attribute" :sku.sync="sku" async />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 扩展属性 -->
      <el-row>
        <el-col :span="18">
          <el-form-item label="扩展属性">
            <el-table :data="extendsPropertiesList" stripe border highlight-current-row>
              <el-table-column v-if="extendsPropertiesList.length > 0" type="index" width="50" align="center" />
              <el-table-column prop="label" label="属性名" min-width="120px" align="center" />
              <el-table-column prop="value" label="属性值" min-width="120px" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" :placeholder="`请输入${scope.row.label}`" size="small" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="0"></el-col>
      </el-row>
      <!-- 商品详情 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品详情">
            <tinymce v-model="formData.detailDesc" :height="300" />
          </el-form-item>
        </el-col>
        <el-col :span="0"></el-col>
      </el-row>
      <!-- 提交按钮 -->
      <el-row>
        <el-col style="text-align:right">
          <el-button @click="onSubmit" type="success">提交</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce';
import UploadImage from '@/components/UploadImage/UploadImage';
import SkuForm from './skuform';

export default {
  data() {
    return {
      formData: {
        merchantId: this.$store.getters.customerId,
        id: null,
        productId: '',
        productName: '', // 商品名称
        categoryCode: '', // 商品分类
        soldPrice: '', // 商品原价
        price: '', // 商品现价
        stock: '', // 库存
        pics: [], // 图片都放在这里 这是最后给后端的   图片列表:0:列表页缩略图；1:详情页轮播图；2:详情页详细介绍图片 ,
        detailDesc: '', // 产品详情，图文详情
        isHot: 0, // 是否设置为热门商品
        isEnableSpec: 0, // 是否启用sku 1-启用 0-不启用 ,
        productItemDTOs: [],
        productSpecDTOS: [],
        extendsProperties: [], // 扩展属性
      },
      formRules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        categoryCode: [
          { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
        soldPrice: [{ required: true, message: '请输入', trigger: 'change' }],
        price: [{ required: true, message: '请输入', trigger: 'change' }],
        stock: [{ required: true, message: '请输入', trigger: 'change' }],
      },

      categoryList: [], // 分类列表
      swiperImageList: [], // 轮播图
      thumbImageList: [], // 缩略图
      imageType: {
        thumb: '0',
        swiper: '1',
      },

      sourceSpceList: [], // 原始规格与属性数据
      sourceAttribute: [],
      attribute: [],
      sku: [],

      extendsPropertiesList: [], // 扩展属性
    };
  },
  mounted() {
    this.$nextTick(async () => {
      this.getCategoryList();
      await this.getProductDetail();
      this.getSpecByCategoryCode();
      // this.getSpecificationList();
    });
  },

  methods: {
    onChangeCascader(e) {
      this.formData.categoryCode = e[e.length - 1];
      this.getSpecByCategoryCode();
    },

    /**
     * 图片上传后回调
     */
    syncImageList(list, type) {
      list.forEach((e) => {
        e.picFun = type;
        e.picUrl = e.url;
        e.productId = this.$route.query.code;
        e.productItemId = 0;
        delete e.hasSuccess;
        delete e.height;
        delete e.width;
        delete e.uid;
      });
    },

    /**
     * 图片分类
     * 扩展url，上传图片组件使用url字段
     */
    extendImageList(type) {
      return (
        this.formData.pics
          .filter((e) => e.picFun === type)
          .map((e) => {
            return {
              ...e,
              ...{ url: e.picUrl },
            };
          }) || []
      );
    },

    /**
     * 获取商品详情
     */
    async getProductDetail() {
      const { code } = this.$route.query;
      if (!code) return;

      const response = await this.$api.getProductDetail(code);
      if (response.success) {
        this.formData = {
          ...{},
          ...response.data,
        };
        this.swiperImageList = this.extendImageList(this.imageType.swiper);
        this.thumbImageList = this.extendImageList(this.imageType.thumb);
        console.log('this.swiperImageList', this.swiperImageList);
        console.log('this.thumbImageList', this.thumbImageList);
        console.log('this.formData', this.formData);
      }
    },

    /**
     * product -> sku|attribute
     */
    convertProductToSku() {
      // sku
      this.sku = [];
      this.formData.productItemDTOs.forEach((e) => {
        const sku = {
          sku: (e.productItemSpecDTOS || [])
            .map((e) => {
              return e.propertyName;
            })
            .join(';'),
          price: e.price,
          stock: e.num,
        };
        this.sku.push(sku);
      });
      // attribute
      this.attribute = [];
      this.formData.productSpecDTOS.forEach((e) => {
        const attr = {
          name: e.specificationName,
          item: e.productSpecPropertyDTOS.map((s) => {
            return s.propertyName;
          }),
        };
        this.attribute.push(attr);
      });

      console.log('this.sku', this.sku);
      console.log('this.attribute', this.attribute);
    },

    /**
     * product -> extends property
     */
    convertProductToProp() {
      this.extendsPropertiesList.forEach((e) => {
        const prop = (this.formData.extendsProperties || []).find(
          (f) => Object.keys(f)[0] === e.label
        );
        if (prop) e.value = prop[e.label];
      });
      console.log('this.extendsPropertiesList', this.extendsPropertiesList);
    },

    async getCategoryList() {
      const { data } = await this.$api.getCategoryList();
      this.categoryList = data;
    },

    async onSubmit() {
      this.$refs.skuForm.validate((valid) => {
        if (valid) {
          const pics = [...this.swiperImageList, ...this.thumbImageList];
          const productItemDTOs = this.convertSkuToProdcut();
          const extendsProperties = this.convertExtendsPropToProduct();
          const params = {
            ...this.formData,
            ...{ pics },
            ...{ productItemDTOs },
            ...{ extendsProperties },
          };
          const { code } = this.$route.query;
          // return;
          if (!code) {
            this.addProduct(params);
          } else {
            this.editProdcut(params);
          }
        }
      });
    },

    /**
     * sku | attribute -> product
     */
    convertSkuToProdcut() {
      console.log('this.sku', this.sku);
      console.log('this.attribute', this.attribute);

      const productItemDTOs = [];
      this.sku.forEach((e) => {
        const productItem = {
          num: e.stock,
          price: e.price,
          productId: this.formData.id,
          productItemSpecDTOS: [],
        };
        e.sku.split(';').forEach((s, i) => {
          const sourceSpec = this.sourceSpceList.find((e) =>
            e.item.some((item) => item.name === s)
          );
          const souceProp = sourceSpec.item.find((e) => e.name === s);
          const specItem = {
            speciPropertyId: souceProp.id,
            propertyName: souceProp.name,
            specificationId: sourceSpec.id,
            specificationName: sourceSpec.name,
          };
          productItem.productItemSpecDTOS.push(specItem);
        });
        productItemDTOs.push(productItem);
      });
      console.log('productItemDTOs', productItemDTOs);
      return productItemDTOs;
    },

    /**
     * extends property -> product
     */
    convertExtendsPropToProduct() {
      console.log('this.extendsPropertiesList', this.extendsPropertiesList);
      return this.extendsPropertiesList.map((e) => {
        return { [e.label]: e.value };
      });
    },

    async addProduct(params) {
      const response = await this.$api.addProduct(params);
      if (response.success) {
        this.$notify({
          title: '添加成功',
          message: '添加成功',
          type: 'success',
        });
        this.gotoList();
      }
    },

    async editProdcut(params) {
      const response = await this.$api.modifyProduct(params);
      if (response.success) {
        this.$notify({
          title: '修改成功',
          message: '修改成功',
          type: 'success',
        });
        this.gotoList();
      }
    },

    gotoList() {
      this.$router.push({ path: '/market/goods' });
    },

    /**
     * 启用产品规格
     */
    onChangeSpecSwitch(e) {
      // 未选择分类
      if (this.formData.categoryCode.length === 0) {
        this.$message.warning('请先选择商品分类');
        this.formData.isEnableSpec = !e;
        return;
      }

      // 选择了无规格的分类
      let currentCategory;
      for (let i = 0; i < this.categoryList.length; i++) {
        const item = this.categoryList[i];
        if (item.categoryCode === this.formData.categoryCode) {
          currentCategory = item;
          break;
        }

        if (item.children && item.children.length > 0) {
          for (let j = 0; j < item.children.length; j++) {
            const subitem = item.children[j];
            if (subitem.categoryCode === this.formData.categoryCode) {
              currentCategory = subitem;
              break;
            }
          }
        }
      }
      if (currentCategory.typeId == null) {
        this.$message.warning('该商品分类未配置规格属性');
        this.formData.isEnableSpec = !e;
        return;
      }

      // 正常
      this.formData.isEnableSpec = e;
      this.getSpecByCategoryCode();
    },

    /**
     * 场景1:商品分类变更时,重新获取规格
     * 场景2:查询商品详情后,获取规格，展示sku并且回显
     * 场景3:启用产品规格后,获取规格，展示sku
     */
    async getSpecByCategoryCode() {
      const params = {
        categoryCode: this.formData.categoryCode,
      };
      const { success, data } = await this.$api.getTemplateInfo(params);
      if (success && data) {
        // 尽在启用时，初始化
        if (data.specTreeDTOs && this.formData.isEnableSpec) {
          this.initSku(data.specTreeDTOs);
          this.convertProductToSku();
        }

        // 有效扩展属性时，初始化
        if (data.extendsProperties) {
          this.initExtendsProperties(data.extendsProperties);
          this.convertProductToProp();
        }
      }
    },

    /**
     * spec list -> sku
     */
    initSku(specList) {
      // sku
      this.sourceAttribute = [];
      specList.forEach((s) => {
        const temp = { name: s.specName, item: [] };
        s.childrens.forEach((p) => {
          temp.item.push(p.propertyName);
        });
        this.sourceAttribute.push(temp);
        this.$refs.skuForm.init();
      });

      // source
      this.sourceSpceList = [];
      specList.forEach((s) => {
        const temp = { id: s.id, name: s.specName, item: [] };
        s.childrens.forEach((p) => {
          temp.item.push({ id: p.id, name: p.propertyName, specId: p.specId });
        });
        this.sourceSpceList.push(temp);
      });
    },

    /**
     * extends property -> list
     */
    initExtendsProperties(propList = []) {
      this.extendsPropertiesList = [];
      propList.forEach((e) => {
        const temp = { label: e, value: '' };
        this.extendsPropertiesList.push(temp);
      });
    },
  },

  components: {
    Tinymce,
    UploadImage,
    SkuForm,
  },
};
</script>

<style lang="scss" scoped>
.box-card-container {
  display: flex;
  flex-wrap: wrap;
}
::v-deep .box-card {
  width: 30%;
  margin: 10px 10px 10px 0px;
  .el-card__header,
  .el-card__body {
    padding: 5px 10px;
  }
}
::v-deep .extends-props-form {
  .el-form-item__label {
    text-align: left;
  }
}
</style>
